package com.beerandjesus.sportofkings.handicapper.factory.brisnet.singlefile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Simple utility to browse contents of Bris single file format data file
 * by index
 * @author mstevens
 */
public class Searcher {
	
	private String[] values;
	private String filePathAqu = "src/test/resources/AQU0207.DRF";
	private String filePathMcp = "src/test/resources/AQU0207.MCP";
	private String filePathCdx = "src/test/resources/CDX0505.DRF";
	private BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		Searcher s = new Searcher();
		
		s.readInFile();
		
		s.waitForInput();

	}

	private void waitForInput() throws IOException {
		
		while(true) {
			System.out.print("Enter an index number, or 'x' to quit: ");
			
			
			
			String input = inReader.readLine();
			
			input = input.trim();
			
			if (input.equalsIgnoreCase("x") || input.equalsIgnoreCase("q")) {
				break;
			}
			
			Integer num = new Integer(input);
			
			String value = values[num - 1];
			
			System.out.println();
			
			System.out.println("Value is: " + value);
			
			System.out.println();
		}
		
		System.out.println("Done.");
		
	}

	private void readInFile() throws IOException {
		String theFilePath = decideTrack();
		
		Integer lineNum = null;
		while (lineNum == null) {
			System.out.print("Enter line number of input file: ");
			String num = inReader.readLine();
			
			try {
				lineNum = new Integer(num);
			} catch (NumberFormatException e) {
			}
		}
		
		
		File f = new File(theFilePath);
		BufferedReader r = new BufferedReader(new FileReader(f));
		for (int i = 1; i < lineNum; i++) {
			System.out.println("Reading line " + i);
			r.readLine();
		}
		System.out.println("Saving line " + lineNum);
		String firstLine = r.readLine();
		
		values = firstLine.split(",");
		
		r.close();
		
	}

	private String decideTrack() throws IOException {
		while (true) {
			System.out.print("Enter AQU, MCP or CDX (or 'x' to exit): ");
			
			String file = inReader.readLine();
			
			if (file.equals("AQU")) {
				return filePathAqu;
			} else if (file.equals("CDX")) {
				return filePathCdx;
			} else if (file.equals("MCP")) {
				return filePathMcp;
			} else if (file.equalsIgnoreCase("x") ||
					file.equalsIgnoreCase("q") ) {
				System.out.println("Done.");
				System.exit(0);
			} else {
				System.out.println();
				System.out.println("Sorry, that's invalid...");
				System.out.println();
			}
		}
	}

}
